<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
  <style>
    #div_body{
	  width:500px;
	  height:500px;
	  border:solid 1px black;
	  margin:auto;
	  position:relative;
	}
	#div_body div{
	  width:50px;
	  height:50px;
	  background-color:red;
      position:absolute;
	}
  </style>
 </head>
 <body>
    <div id="div_body">
	  <div id="div_1"></div>
	</div>
 </body>
   <script>
      var div_1 = new div1(document.getElementById("div_1"));
	  document.addEventListener("keydown",function(evt){
	      var code = evt.keyCode;
		  console.log(code);
		  switch(code){
		   case 38: //上
		     div_1.moveTop();
		     break;
		   case 40: //下
		     div_1.moveBottom();
             break;
		   case 37: //左
		     div_1.moveLeft();
             break;
		   case 39: //右
		     div_1.moveRight();
		     break;
		  }
	  })
      
	  function div1(div_1){
         var div_body = document.getElementById("div_body");
		 this.div = div_1;
		 this.x = div_body.offsetWidth;
		 this.y = div_body.offsetHeight;
         this.w = this.div.offsetWidth;
		 this.h = this.div.offsetHeight;
		 this.xw = 0;
		 this.yh = 0;
         this.div.style.position = "absolute";
         
		 this.moveRight = function(){
			if(this.div.offsetLeft + this.w + 5 < this.x){
			  this.xw += 5;
		      this.div.style.left = this.xw+"px";
			}	 
		 }
		 this.moveLeft = function(){
			if(this.div.offsetLeft > 0){
		    this.xw-= 5;
			this.div.style.left = this.xw+"px";
			}
		 }
		 this.moveBottom = function(){
			if(this.div.offsetTop + this.h + 5 < this.y){
			    this.yh += 5;
				this.div.style.top = this.yh+"px";
			}
		 }
		 this.moveTop = function(){
		    if(this.div.offsetTop > 0){
			   this.yh -= 5;
			   this.div.style.top = this.yh+"px";
			}
		 }
	  }
   </script>
</html>
